const createError = require('http-errors');
const express = require('express');
const expressWs = require('express-ws');
const path = require('path');
const cookieParser = require('cookie-parser');
const logger = require('morgan');
const ejs = require('ejs');
// const compression = require('compression')
const https = require('https')
const fs = require('fs')

const indexRouter = require('./routes/index');
const uploadRouter = require('./routes/upload');
const wsRouter = require('./routes/ws');

const app = express();
// https option
const options = {
  cert: fs.readFileSync('./keys/apk.yywis.com.pem'),
  key: fs.readFileSync('./keys/apk.yywis.com.key')
}
// app.use(compression())

// io

// 允许跨域
app.all('*', function (req, res, next) {

  // 307 https --
  // if (req.protocol != "https") {
  //   let host = req.headers.host;
  //   host = host.replace(/\:\d+$/, ''); // Remove port number
  //   console.log('host:' + host);
  //   res.redirect(307, `https://${host}:9989${req.path}`)
  // }
  
  // console.log(req.headers.origin)
  // console.log(req.environ)
  // res.header("Access-Control-Allow-Origin", req.headers.origin);
  res.header("Access-Control-Allow-Origin", '*');
  res.header("Access-Control-Allow-Headers", "Content-Type,Content-Length, Authorization, Accept,X-Requested-With");
  res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
  res.header("Access-Control-Allow-Credentials", "true");
  res.header("X-Powered-By", ' 3.2.1')
  
  if (req.method === "OPTIONS") res.send(200);/*让options请求快速返回*/
  else next();
});

app.use('/files',express.static('./files'));
app.use('/modules',express.static('./modules'));
// 设置视图目录和模板引擎
app.set('views', path.join(__dirname, 'views'));
app.engine('.html',ejs.__express);
app.set('view engine','html');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use("/public", express.static(path.join(__dirname, 'public')));
app.use("/log", express.static(path.join(__dirname, 'log')));
// app.use(express.static(path.join(__dirname,'views/')))
// app.use('/',express.static('./views'));

// 引进路由
app.use('/', indexRouter);
app.use('/upload', uploadRouter);
app.use('/ws', wsRouter);
// socket.io


// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

// 监听端口
app.listen(80, '0.0.0.0', function () {
  console.log('Express is running... port:80')
})

// var server = https.createServer(options, app)
// server.listen(9989, ()=>{
//     console.log('https server running... 9989')
//     init_wss(server)
// })

// let init_wss = require("./routes/wss")


